//
//  LXJTextView.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/4/5.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit

class LXJTextView: UITextView {

    //  占位 placeHolderLabel
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.text = "请求输入内容"
        label.textColor = UIColor.lightGray
        label.font = UIFont.systemFont(ofSize: 12)
        //  多行显示
        label.numberOfLines = 0
        return label
    }()
    
    //  占位文字
    var placeHolder: String? {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    // 占位文字大小
    override var font: UIFont? {
        didSet {
            if font != nil {
                placeHolderLabel.font = font
            }
        }
    }
    
    // textView 的文字
    override var text: String? {
        didSet {
            //  判断hasText表示文本框是否有内容
            placeHolderLabel.isHidden = self.hasText
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        // 添加子控件
        addSubview(placeHolderLabel)
        
        //  手写代码自动布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 7))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
        
        // 使用通知监听文字改变
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
    }
    
    //  MARK: --- 监听文字改变
    @objc private func textChange() {
        //  如果有内容,隐藏占位文字
        placeHolderLabel.isHidden = hasText
    }
    
    // 移除通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
